package com.saxion.dao;

import java.util.ArrayList;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.TransactionSystemException;

import com.saxion.model.Bestelling;
import com.saxion.model.Klant;

public class KlantDaoImpl implements KlantDao {

 private SessionFactory sessionFactory;
     
     public SessionFactory getSessionFactory() {return sessionFactory;}

     public void setSessionFactory(SessionFactory sessionFactory) {
         this.sessionFactory = sessionFactory;
     }

	
	@Override
	public Klant getKlant(String naam) {
		Session session = null;
		ArrayList<Klant> klanten = new ArrayList<Klant>();
		try{
			
			try{
				session = sessionFactory.getCurrentSession();
			}catch(HibernateException e){
				session = sessionFactory.openSession();
			}
			klanten = (ArrayList<Klant>) session.createCriteria(Klant.class).add(Restrictions.eq("naam", naam)).list();
			//klanten = (ArrayList<Klant>) session.createQuery("from Klant where naam = ?").setString(0, naam).list();
			 
			 
			session = sessionFactory.getCurrentSession();
		}catch(HibernateException e){
			session = sessionFactory.openSession();
			
		}
		catch(TransactionSystemException e){
			//e.printStackTrace();
//			session.close();
			return null;
		}catch(Exception e){
//			session.close();
			return null;
		}
		finally{
			session.close();
		}
		if(klanten.isEmpty()){
			return null;
		}
		return klanten.get(0);
	}

	@Override
	public long addKlant(String naam) {
		Klant klant = new Klant(naam);
		Session session = null;
		
        Transaction txD = null;
        try{
        	try{
    			session = sessionFactory.getCurrentSession();
    		}catch(HibernateException e){
    			session = sessionFactory.openSession();
    		}
        	if (session.getTransaction() != null
    	            && session.getTransaction().isActive()) {
    	        txD = session.getTransaction();
    	    } else {
    	        txD = session.beginTransaction();
    	    }
			session.save(klant);
	        txD.commit();			
        }catch( HibernateException e){
        	if(txD !=null){
        		txD.rollback();
        	}
        	e.printStackTrace();
        } finally{
        	session.close();
        }
        
        return klant.getID();

	}

}
